import axios from "axios"
import qs from "qs"
import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import { token } from '../../build/config'
import {getToken} from '@/utils/auth'

const getType = o => {
  return Object.prototype.toString.call(o).replace(/(\[object\s|\])/g, "");
};

const isStringAndNumber = data => {
  if (getType(data) === "String" || getType(data) === "Number") return true;
  return false;
};

const instance = axios.create({
  headers: {
    "Content-Type": "application/json;charset=UTF-8"
    // 'Content-Type': 'application/json'
    // 'Content-Type': 'multipart/form-data'
    // "Cache-Control": "no-cache,no-store,must-revalidate,max-age=-1,private",
  },
  transformRequest: [
    function(data, config) {
      if (isStringAndNumber(data)) data = null;
      if (config["Content-Type"] === "application/x-www-form-urlencoded")
        data = qs.stringify(data);
      if (config["Content-Type"] === "application/json")
        data = JSON.stringify(data);
      if (config["Content-Type"] === "multipart/form-data")
        data = JSON.stringify(data);
      if (config["Content-Type"] === "application/json;charset=UTF-8")
        data = JSON.stringify(data);

      config["accept-language"] = localStorage.lang;
      return data;
    }
  ],
  // withCredentials: true,
  timeout: 60000
});

instance.interceptors.request.use(config => {
  //设置头部
  // console.log(getToken())
  //设置content-type
  if (config.ContentType) config.headers["Content-Type"] = config.ContentType;
  //设置token
  if (getToken()) {
    config.headers['qa-token'] = getToken();
  }
  //设置请求体格式
  if (!config.data) config.data = {};
  if (config.method === "get" || config.method === "delete") {
    config.params = config.data;
  }
  return config;
});

instance.interceptors.response.use(
  response => {
    const { config } = response;

    const res = response.data || {};
    if (config.hideLoading) config.hideLoading();
    // console.log(`${response.request.responseURL}:  ${JSON.stringify(res)}`)

    if (
      res &&
      (config.analysisCode ||
        res.code === 200 ||
        res.code === 0 ||
        res.message === "ok")
    ) {
      config.showMsg && Message.success(res.message);
      return res.body || res.data || res;
    } else {
      let message = (res && res.message) || response.status;
      if (res.code === 50003)
        message = res.message + "：" + res.details.join(",");
      Message.error(message);

      return Promise.reject(res);
    }
  },
  error => {
    if (error.config && error.config.hideLoading) error.config.hideLoading();

    if (
      error.response.data &&
      error.response.data.code &&
      error.response.data.code === 10001
    ) {
      Message.error(error.response.data.message);
      setTimeout(() => {
        store.dispatch("logout");
      }, 150);
    } else {
      Message.error(error.message);
    }

    return Promise.reject(error);
  }
);

export default instance;
